mod debug;
mod map;
mod player;
mod ui;

use bevy::{
    diagnostic::{DiagnosticsStore, FrameTimeDiagnosticsPlugin},
    prelude::*,
};
use debug::DebugPlugins;
use map::map::MapPlugins;
use player::{player::Player, PlayerPlugins};
use ui::UiPlugins;

/// 窗口宽度
static WIN_W: f32 = 960.;
/// 窗口高度
static WIN_H: f32 = 720.;
fn main() {
    App::new()
        .add_plugins(DefaultPlugins.set(WindowPlugin {
            primary_window: Some(Window {
                title: "mini Game".into(),
                resolution: (WIN_W, WIN_H).into(),
                resizable: true,
                decorations: true,
                ..default()
            }),
            ..default()
        }))
        .add_plugins((
            MapPlugins,
            DebugPlugins,
            PlayerPlugins,
            UiPlugins,
            FrameTimeDiagnosticsPlugin,
        ))
        .add_systems(Startup, (spawn_camera, spawn_fps_ui))
        .add_systems(Update, (move_camera, show_fps))
        .run();
}
/// 2d相机
fn spawn_camera(mut commands: Commands) {
    let camera = Camera2dBundle {
        transform: Transform::from_xyz(0.0, 0.0, 0.0),
        ..default()
    };
    commands.spawn(camera);
}

//相机跟随角色
fn move_camera(
    time: Res<Time>,
    mut camera_query: Query<&mut Transform, With<Camera>>,
    player_query: Query<&mut Transform, (With<Player>, Without<Camera>)>,
) {
    let mut camera_transform = camera_query.single_mut();
    let player_transform = player_query.single();
    camera_transform.translation = lerp(
        camera_transform.translation,
        player_transform.translation,
        time.delta_seconds() * 3.,
    );
}

fn lerp(start: Vec3, end: Vec3, t: f32) -> Vec3 {
    start * (1.0 - t) + end * t
}

#[derive(Component)]
pub struct FSPUi;

fn spawn_fps_ui(mut com: Commands, asset_server: Res<AssetServer>) {
    com.spawn((
        FSPUi,
        TextBundle::from_sections([
            TextSection::new(
                "FPS: ",
                TextStyle {
                    font: asset_server.load("ttf/fusion-pixel.ttf"),
                    font_size: 30.,
                    color: Color::RED,
                    ..default()
                },
            ),
            TextSection::from_style(TextStyle {
                font: asset_server.load("ttf/fusion-pixel.ttf"),
                font_size: 30.,
                color: Color::RED,
                ..default()
            }),
        ])
        .with_style(Style {
            position_type: PositionType::Absolute,
            bottom: Val::Px(0.),
            left: Val::Px(0.),
            ..default()
        }),
    ));
}

fn show_fps(mut query: Query<&mut Text, With<FSPUi>>, diag: Res<DiagnosticsStore>) {
    let mut text = query.single_mut();
    let Some(fps) = diag
        .get(&FrameTimeDiagnosticsPlugin::FPS)
        .and_then(|fps| fps.smoothed())
    else {
        return;
    };
    text.sections[1].value = format!("{:.00}", fps);
}
